<?php

require_once( 'flexical/service/metadata.php' );
require_once( 'flexical/service/constants.php' );
require_once( 'flexical/service/lock.php' );

class Flexical_Service_Storage
{
	public $type;

	private $option_name;

	private $lock;

	public function __construct( $type )
	{
		$this->option_name = Flexical_Service_Constants::$OPTION_PREFIX . $type;
		$this->lock = new Flexical_Service_Lock( 'storage-' . $type );
	}

	private function get_meta()
	{
		return get_option( $this->option_name );
	}

	private function update_meta( $meta )
	{
		update_option( $this->option_name, $meta );
	}

	public function create( $object )
	{
		$this->lock->lock();

		$meta = $this->get_meta();
		$object->id = $meta->next_id++;
		$meta->objects[ $object->id ] = clone $object;
		$this->update_meta( $meta );

		$value = $meta->objects[ $object->id ];

		$this->lock->unlock();
		return $value;
	}

	public function read( $id = null )
	{
		$this->lock->lock();

		$value = $id == null ? $this->get_meta()->objects : $this->get_meta()->objects[ $id ];

		$this->lock->unlock();
		return $value;
	}

	public function update( $object )
	{
		$this->lock->lock();

		$meta = $this->get_meta();
		$meta->objects[ $object->id ] = clone $object;
		$this->update_meta( $meta );

		$this->lock->unlock();
	}

	public function delete( $id )
	{
		$this->lock->lock();

		$meta = $this->get_meta();
		unset( $meta->objects[ $id ] );
		$this->update_meta( $meta );

		$this->lock->unlock();
	}

	public function install()
	{
		$this->lock->lock();

		add_option( $this->option_name, new Flexical_Service_Metadata() );

		$this->lock->unlock();
	}

	public function uninstall()
	{
		$this->lock->lock();

		delete_option( $this->option_name );

		$this->lock->unlock();
	}
}

?>
